package ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.devicecontroller.command;

import net.wimpi.modbus.msg.ModbusRequest;
import net.wimpi.modbus.msg.ModbusResponse;
import net.wimpi.modbus.msg.ReadMultipleRegistersRequest;
import net.wimpi.modbus.msg.ReadMultipleRegistersResponse;

public class BitRegisterCommand extends RegisterCommand implements BitCommand{
	
	private boolean bit;
	private int offset;
	
	public BitRegisterCommand(){
		super();
	}
	
	@Override
	public boolean needRetrieve() {
		return true;
	}

	@Override
	public ModbusRequest getRetriveRequest() {
		return new ReadMultipleRegistersRequest(getAddress(), 1);
	}

	@Override
	public void setRetrieveResponse(ModbusResponse res) throws CommandException {
		int mask;
		int newValue;
		int value;
		
		if( res instanceof ReadMultipleRegistersResponse ){
			value = (( ReadMultipleRegistersResponse ) res ).getRegisterValue(0);
			newValue = (isBit() ? 0x01 : 0x00) << getOffset();
			mask =  (0xFFFF)^ (0x01 << getOffset() );
			value = (value & mask) | newValue;
			setValue(value);
		}
		else {
            throw new CommandException("Response is incorrect");
		}
		
	}

	/**
	 * @return the bit
	 */
	public boolean isBit() {
		return bit;
	}

	/**
	 * @param bit the bit to set
	 */
	public void setBit(boolean bit) {
		this.bit = bit;
	}

	/**
	 * @return the offset
	 */
	public int getOffset() {
		return offset;
	}

	/**
	 * @param offset the offset to set
	 */
	public void setOffset(int offset) {
		this.offset = offset;
	}

}
